package com.hu.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesUtils {

    private static Properties properties= new Properties();

    /*properties文件名*/
    private static String propertyPath;

    static {
        String projectPath = System.getProperty("user.dir") + "\\..\\..";
        try {
            projectPath = new File(projectPath).getCanonicalFile().getAbsolutePath();
            propertyPath = projectPath+"\\config.properties";
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 初始化properties，即载入数据
     */
    private static void initProperties(){
        try {
            File file = new File(propertyPath);
            if(!file.exists()){
                file.createNewFile();
            }
            properties.load(new FileInputStream(propertyPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**将数据载入properties，并返回"lastid"的值
     * @return
     */
    public static String getKey(String key){
        if(properties.isEmpty())//如果properties为空，则初始化一次。
            initProperties();
        return properties.getProperty(key); //properties返回的值为String，转为整数
    }

    /**修改lastid的值，并保存
     */
    public static void saveKey(String key,String value){
        if(properties.isEmpty())
            initProperties();
        //修改值
        properties.setProperty(key, value);
        //保存文件
        try {

            FileOutputStream stream = new FileOutputStream(new File(propertyPath));
            properties.store(stream, "the primary key of article table");
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
